
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>laychat聊天室</title>
    <meta property="qc:admins" content="347437765760473736375716450600070755737774574113014" />
    <link rel="stylesheet" href="/Public/Swoole/layui/css/layui.css">
    <link rel="stylesheet" href="/Public/Swoole/css/laychat.css">
    <script type="text/javascript" src="/Public/js/jquery-1.8.2.min.js"></script>
    <script src="/Public/Swoole/layui/layui.js"></script>
    <style>
        html{background-color: #D9D9D9;}
    </style>
</head>
<body>

<script type="text/javascript"
        src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js"
        data-appid="101341036"
        data-redirecturi="http://www.pdosgk.com/index.php/Home/Swoole/laychat_login"
        charset="utf-8">
</script>

<div class="desc">
    <p class="content">
        此作品为
        <a href="http://layim.layui.com/" target="_blank">LayIM</a>
        配合
        <a href="http://www.workerman.net" target="_blank">workerman</a>
        的经典案例
    </p>
    <p>
        <a href="http://www.layui.com/doc/layim.html" target="_blank">LayIM文档</a>
        <a href="http://www.workerman.net/gatewaydoc/" target="_blank">workerman文档</a>
        <a href="https://github.com/walkor/laychat" target="_blank">后端源码</a>
    </p>
    <p class="qq_login">
        <span id="qqLoginBtn"></span>
    </p>
</div>


<script type="text/javascript">
    // QQ互联
    userinfo = {}, client_list = {};
    var notify = false;
   QC.Login({
       btnId:"qqLoginBtn",    
       scope:"get_user_info",
       size: "A_L"
   }, function(reqData, opts){QC.Login.getMe(function(openId, accessToken){
           userinfo['openid'] = openId;
           userinfo['avatar'] = reqData.figureurl_qq_1;
           userinfo['gender']   = reqData.gender;
           userinfo['nickname'] = reqData.nickname;
           connect_workerman();
           setInterval('send_heartbeat()', 20000);
           var dom = document.getElementById(opts['btnId']),
           _logoutTemplate=[
               //头像
               '<span><img src="{figureurl}" class="logout_icon"/></span>',
               //昵称
               '<span>{nickname}</span>',
               //退出
               '<span><a href="javascript:QC.Login.signOut();">退出</a></span>'
           ].join("");
           dom && (dom.innerHTML = QC.String.format(_logoutTemplate, {
               nickname : QC.String.escHTML(reqData.nickname), //做xss过滤
               figureurl : reqData.figureurl_qq_1
           }));
       });
   }, function(opts){
	   //注销成功
       location.reload();
   });

function connect_workerman(){
    socket = new WebSocket('ws://'+document.domain+':9510');
    socket.onopen = function(){
        var init_data = userinfo;
        init_data['type'] = 'init';
        console.log(JSON.stringify(init_data));
        socket.send(JSON.stringify(init_data));
    };

    socket.onmessage = function(e){
        var msg = JSON.parse(e.data);
        console.log(msg);
        switch(msg.message_type) {
            case 'init':
            	userinfo['userid'] = msg.userid;
                initim(msg.userid);
                return;
        }
    };
    socket.onclose = function(e){
        connect_workerman();
        notify = false;
    };
    
}

// 发送心跳，防止链接长时间空闲被防火墙关闭
function send_heartbeat(){
    if(socket && socket.readyState == 1) {
        socket.send(JSON.stringify({type :'ping'}));
    }
}
// 初始化聊天窗口
function initim(userid){
    layui.use(['layim', 'socket', 'layer'], function(layim){
    	//如果列表不为空
        for (var p in client_list) {
            layim.removeList({
                type: 'friend', //或者group
                id: p //好友或者群组ID
            });
        }
        client_list = {};
    	var layer = layui.layer;
    	
        //基础配置
        layim.config({

            //初始化接口
            init: {
                url: '/index.php/Home/Swoole/ajax_getList/userid/'+userid
                ,data: {}
            }

            //查看群员接口
            ,members: {
                url: './get_members.php'
                ,data: {}
            }

            ,uploadImage: {
                url: './upload_img.php'
            }

            ,uploadFile: {
                url: './upload_file.php'
            }

            ,chatLog: './demo/chatlog.html?id=' //聊天记录地址
            ,find: './demo/find.html'
            ,copyright: true //是否授权
        });
        
      

        //监听发送消息
        layim.on('sendMessage', function(data){
            /* socket.send(JSON.stringify({
                type: 'chatMessage'
                ,data: data
            })); */
            var To = data.to;
            var message_data = '{"type":"chatMessage","to_client_id":' + To.id + ',"username":"' + data.mine.username + '", "avatar":"' + data.mine.avatar + '", "content":"' + data.mine.content.replace(/"/g, '\"') + '"}';
            //发送消息倒Socket服务

            console.log(message_data);
            socket.send(message_data);
        });

        //监听在线状态的切换事件
        layim.on('online', function(data){
            socket.send(JSON.stringify({type: data}));
        });

        //layim建立就绪
        layim.on('ready', function(res){
        	//建立成功，通知登陆
        	if(!notify){
        		var login_data = '{"type":"login","username":"' + userinfo['nickname'].replace(/"/g, '\"') + '", "avatar":" '+userinfo['avatar']+'","userid":' + userid + '}';
                
                console.log("websocket握手成功，发送登录数据:" + login_data);
                socket.send(login_data);
                notify = true;
        	}
            
            
            socket.onmessage = function(e){
                var data = JSON.parse(e.data);
                console.log(data);
                switch(data.message_type) {
                    case 'login':
                    	if (data['client_list']) {
                            client_list = data['client_list'];
                            friend_list();
                        } else {
                            client_list[data['userid']] = {
                                'userid': data['userid'],
                                'username': data['username'],
                                'avatar': data['avatar']
                            };
                            friend_list_new(data['userid'], data['username'], data['avatar']);
                        }
                        console.log(data['username'] + "登录成功");
                    	break;
/*                     case 'addList':
                        if($('#layim-friend'+msg.data.id).length == 0 && userinfo['id'] != msg.data.id){
                            return layim.addList(msg.data);
                        }
                        $('#layim-friend'+msg.data.id+' img'). removeClass('gray_icon');
                        return; */
                    case 'chatMessage':
                        layim.getMessage(data);
                        return;
                    case 'logout':
                    	layim.removeList({
                            type: 'friend', //或者group
                            id: data['userid'] //好友或者群组ID
                        });
                        delete client_list[data['userid']];
                        break;
                    case 'hide':
                        $('#layim-friend'+data.userid+' img').addClass('gray_icon');
                        return;
                    case 'online':
                        $('#layim-friend'+dada.id+' img').removeClass('gray_icon');
                        return;
                }
            }
        });

        function friend_list() {
            //获取列表
            for (var p in client_list) {
                if (userinfo['userid'] != client_list[p]['userid']) {
                    layim.addList({
                        type: 'friend',
                        avatar: client_list[p]['avatar'],
                        username: client_list[p]['username'],
                        groupid: 2,
                        id: client_list[p]['userid'],
                        remark: ""
                    });
                }
            }

        }

        function friend_list_new(user_id, name, avatar) {
            //如果重复登陆， 当前用户下线
            if (user_id == userid) {
                alert("在别处登陆l");
                socket.close();
                window.close();
            }
            layer.msg("【" + name + '】上线了，打开在线好友列表和TA聊聊吧', {
                shift: 6,
                offset: 0,
                time: 9000
            });

            //新成员
            layim.addList({
                type: 'friend',
                avatar: avatar,
                username: name,
                groupid: 2,
                id: user_id,
                remark: ""
            });
        }

        //监听查看群员
        layim.on('members', function(data){
            console.log(data);
        });

        //监听聊天窗口的切换
        layim.on('chatChange', function(data){
            console.log(data);
        });
    });
}
</script>
</body>
</html>
